#!/usr/bin/env node
/**
 * 数据迁移脚本：为现有用户添加 chainId
 * 使用方法: node scripts/migrate-chain-id.js
 */

const { Client } = require('pg');
require('dotenv').config();

async function migrateChainId() {
    const client = new Client({
        host: process.env.DB_HOST || 'localhost',
        port: process.env.DB_PORT || 5432,
        database: process.env.DB_NAME || 'rwa_platform',
        user: process.env.DB_USERNAME || 'rwa_user',
        password: process.env.DB_PASSWORD || 'rwa_password',
    });

    try {
        console.log('🔄 开始数据迁移...');

        // 连接数据库
        await client.connect();
        console.log('✅ 数据库连接成功');

        // 检查 chainId 列是否存在
        const checkColumnQuery = `
            SELECT column_name 
            FROM information_schema.columns 
            WHERE table_name = 'users' AND column_name = 'chainId'
        `;

        const columnExists = await client.query(checkColumnQuery);

        if (columnExists.rows.length === 0) {
            console.log('📝 添加 chainId 列...');

            // 添加 chainId 列，允许 NULL 值
            await client.query(`
                ALTER TABLE users 
                ADD COLUMN "chainId" integer
            `);
            console.log('✅ chainId 列添加成功');
        } else {
            console.log('ℹ️  chainId 列已存在');
        }

        // 更新现有用户的 chainId 为默认值 1 (Ethereum Mainnet)
        console.log('🔄 更新现有用户的 chainId...');
        const updateResult = await client.query(`
            UPDATE users 
            SET "chainId" = 1 
            WHERE "chainId" IS NULL
        `);

        console.log(`✅ 更新了 ${updateResult.rowCount} 个用户的 chainId`);

        // 创建复合唯一索引
        console.log('📝 创建复合唯一索引...');
        try {
            await client.query(`
                CREATE UNIQUE INDEX "IDX_users_walletAddress_chainId" 
                ON users ("walletAddress", "chainId")
            `);
            console.log('✅ 复合唯一索引创建成功');
        } catch (error) {
            if (error.message.includes('already exists')) {
                console.log('ℹ️  复合唯一索引已存在');
            } else {
                throw error;
            }
        }

        // 验证迁移结果
        console.log('🔍 验证迁移结果...');
        const verifyResult = await client.query(`
            SELECT 
                COUNT(*) as total_users,
                COUNT("chainId") as users_with_chain_id,
                COUNT(*) - COUNT("chainId") as users_without_chain_id
            FROM users
        `);

        const stats = verifyResult.rows[0];
        console.log('📊 迁移统计:');
        console.log(`   总用户数: ${stats.total_users}`);
        console.log(`   有 chainId 的用户: ${stats.users_with_chain_id}`);
        console.log(`   无 chainId 的用户: ${stats.users_without_chain_id}`);

        if (stats.users_without_chain_id > 0) {
            console.log('⚠️  警告: 仍有用户没有 chainId');
        } else {
            console.log('✅ 所有用户都有 chainId');
        }

        console.log('🎉 数据迁移完成！');

    } catch (error) {
        console.error('❌ 迁移失败:', error.message);
        process.exit(1);
    } finally {
        await client.end();
        console.log('🔌 数据库连接已关闭');
    }
}

// 运行迁移
if (require.main === module) {
    migrateChainId().catch(console.error);
}

module.exports = { migrateChainId };
